<template>
  <div>
    <div class="org-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>营销组织管理</el-breadcrumb-item>
        <el-breadcrumb-item>营销组织</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="org-container">
      <div class="org-content">
        <div class="org-header">
          <span>营销组织</span>
          <el-button type="primary" plain @click="addPerson()">配置组织人员</el-button>
        </div>
        <div class="org-body">
          <div class="org-tree">
            <div class="tree-header">
              <div>组织机构列表</div>
              <el-button @click="add()" type="text">添加</el-button>
            </div>
            <div class="tree-content">
              <el-tree
                :render-content="renderContent"
                :data="organizationList"
                :props="organizationListProps"
                @node-click="handleNodeClick"
              ></el-tree>
            </div>
          </div>
          <div class="org-list">
            <div class="org-operation">
              <div>
                <span class="org-label">所属机构</span>
                <el-cascader
                  :options="organizationList"
                  v-model="selectedOrgForDetail"
                  :props="organizationListProps"
                  class="org-list-cascader"
                  change-on-select
                  clearable
                  size="mini"
                ></el-cascader>
              </div>
              <div class="org-position">
                <span class="org-label">岗位</span>
                <el-select v-model="postId" placeholder="请选择岗位" size="mini">
                  <el-option
                    key=""
                    label="全部"
                    value="">
                  </el-option>
                  <el-option
                    v-for="item in postList"
                    :key="item.id"
                    :label="item.postName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div class="org-filter">
                <el-input v-model="filterStr" size="mini" placeholder="姓名/员工号/手机/邮件"></el-input>
              </div>
              <div class="org-label">共{{total}}条数据</div>
              <div>
                <el-button type="primary" size="mini" @click="onSearch()">搜索</el-button>
              </div>
              <div>
                <a :href="downloadUrl" class="org-link" download>模板下载</a>
                <el-upload
                  class="upload-demo"
                  :action="uploadUrl"
                  :data="uploadConfig"
                  :headers="headers"
                  name="file"
                  :show-file-list="false"
                  :multiple="false"
                  :file-list="fileList"
                  :on-success="onUpload">
                  <el-button size="small" type="text">批量导入</el-button>
                </el-upload>
              </div>
            </div>
            <el-table
              :data="tableData"
              style="width: 100%"
            >
              <el-table-column
                prop="employeeId"
                label="员工编号">
              </el-table-column>
              <el-table-column
                prop="name"
                label="姓名">
              </el-table-column>
              <el-table-column
                prop="organizationName"
                label="所属机构">
              </el-table-column>
              <el-table-column
                prop="postName"
                label="岗位">
              </el-table-column>
              <el-table-column
                prop="positionName"
                label="职位">
              </el-table-column>
              <el-table-column
                prop="phone"
                label="手机号"
                width="120">
              </el-table-column>
              <el-table-column
                prop="email"
                label="邮箱"
                width="120">
              </el-table-column>
              <el-table-column label="操作" width="130">
                <template slot-scope="scope">
                  <el-button type="text" @click="showPerson(scope.row)">查看/编辑</el-button>
                  <el-button type="text" @click="deletePerson(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              style="float: right"
              layout="prev, pager, next"
              :total="total"
              @current-change="onSearch">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      title="维护组织机构"
      :visible.sync="orgTreeVisible"
      :close-on-click-modal="false"
      width="60%">
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="创建人">
          <el-input v-model="form.creator" :disabled="true" ></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="form.createTime" :disabled="true" ></el-input>
        </el-form-item>
        <el-form-item label="机构名称" prop="name">
          <el-input v-model="form.name" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item label="上级机构" prop="orgArrId">
          <el-cascader
            :options="organizationList"
            v-model="form.orgArrId"
            :props="organizationListProps"
            @change="selectOrganization"
            change-on-select
          ></el-cascader>
        </el-form-item>
        <el-form-item label="机构分类">
          <el-input v-model="type" :disabled="true" ></el-input>
        </el-form-item>
        <el-form-item label="机构地址" prop="addressArr">
          <el-cascader
            :options="locationList"
            v-model="form.addressArr"
            :props="locationProps"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="" prop="addressDetail">
          <el-input v-model="form.addressDetail" maxlength="160" prop="addressDetail" placeholder="详细地址"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" maxlength="160" v-model="form.remarks"></el-input>
        </el-form-item>
        <el-form-item>
          <div class="dialog-footer">
            <el-button type="primary" @click="onSubmit">立即创建</el-button>
            <el-button @click="onCancel">取 消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="配置组织人员"
      :visible.sync="addPersonPanelVisible"
      :close-on-click-modal="false"
      width="60%">
      <el-form :inline="true" ref="addPersonForm" :model="addPersonForm" :rules="rules1" label-width="80px">
        <el-form-item label="姓名" prop="name" required>
          <el-input v-model="addPersonForm.name"></el-input>
        </el-form-item>
        <el-form-item label="员工号" prop="employeeId" required>
          <el-input v-model="addPersonForm.employeeId"></el-input>
        </el-form-item>
        <el-form-item label="岗位" prop="postId" required>
          <el-select v-model="addPersonForm.postId" placeholder="请选择岗位">
            <el-option
              v-for="item in postList"
              :key="item.id"
              :label="item.postName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="positionId" required>
          <el-select v-model="addPersonForm.positionId" placeholder="请选择职位">
            <el-option
              v-for="item in positionList"
              :key="item.id"
              :label="item.positionName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮件地址" prop="email" required>
          <el-input v-model="addPersonForm.email"></el-input>
        </el-form-item>
        <el-form-item label="所属机构" prop="addPersonOrg" required>
          <el-cascader
            :placeholder="addPersonForm.organizationName || '请选择机构'"
            :options="organizationList"
            v-model="addPersonForm.addPersonOrg"
            :props="organizationListProps"
            change-on-select
          ></el-cascader>
        </el-form-item>
        <el-form-item label="手机号" prop="phone" required>
          <el-input v-model="addPersonForm.phone"></el-input>
        </el-form-item>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPerson">确定</el-button>
          <el-button @click="onCancelAddPerson">取 消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'
  export default {
    name: "list",
    data() {
      const validate = function(rule, value, callback) {
        if (value && value.length > 0) {
          callback();
        } else {
          callback(new Error('请输入密码'));
        }
      }
      const orgValidate = (rule, value, callback) => {
        if (this.organizationList.length === 0 || (value && value.length > 0)) {
          callback();
        } else {
          callback(new Error('请选择上级机构'));
        }
      }
      return ({
        organizationList: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        locationProps: {
          children: 'children',
          label: 'name',
          value: 'name'
        },
        organizationListProps: {
          children: 'children',
          label: 'name',
          value: 'id'
        },
        ownerProps: {
          children: 'children',
          label: 'label',
          value: 'id',
        },
        orgTreeVisible: false,
        addPersonPanelVisible: false,
        form: {},
        addPersonForm: {},
        addressOptions: [],
        selectedNode: {},
        selectedOrgForDetail: [],
        addPersonOrg: [],
        filterStr: '',
        postId: '',
        positionList: [],
        postList: [],
        tableData: [],
        total: 0,
        lastQuery: {},
        fileList: [],
        rules: {
          addressDetail: [
            { required: true, message: '请填写详细地址', trigger: ['blur', 'change'] }
          ],
          addressArr: [
            { required: true, message: '请选择机构地址', trigger: ['blur', 'change'] }
          ],
          name: [
            { required: true, message: '请填写机构名称', trigger: ['blur', 'change'] }
          ],
          orgArrId: [
            { validator: orgValidate, trigger: 'change' }
          ],
        },
        rules1: {
          name: [
            { required: true, message: '请填写姓名', trigger: ['blur', 'change'] }
          ],
          employeeId: [
            { required: true, message: '请填写员工号', trigger: ['blur', 'change'] }
          ],
          postId: [
            { required: true, message: '请选择岗位', trigger: ['blur', 'change'] }
          ],
          positionId: [
            { required: true, message: '请选择职位', trigger: ['blur', 'change'] }
          ],
          email: [
            { required: true, message: '请填写邮件地址', trigger: ['blur', 'change'] },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ],
          addPersonOrg: [
            { validator: validate, message: '请选择所属机构', trigger: 'change' }
          ],
          phone: [
            { required: true, message: '请填写手机号', trigger: ['blur', 'change'] }
          ],
        },
        uploadUrl: '/front/excelUpload',
        // uploadUrl: '/front/file/uploadFile',
        uploadConfig: {
          method: 'File_ImportEmployee',
          // type: 'Document'
        },
      })
    },
    computed: {
      type: function() {
        const lastId = _.last(this.form.orgArrId)
        return this.form.orgArrId && this.form.orgArrId.length > 0 ? _.last(this.getPathByKey(lastId, 'id', this.organizationList).map(item => item.level)) : 1
      },
      downloadUrl: function() {
        return '/file/download?fileName=组织机构人员.xlsx'
      },
      headers: function() {
        let token = sessionStorage.getItem("tokenName")
        return ({
          dipsToken: token,
        })
      }
    },
    mounted() {
      this.getData()
      this.locationList()
      this.getOrganizationInfo()
      this.onSearch()
    },
    methods: {
      getData() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$http.post(this.GLOBAL.host, {
          "method":"organizationTree",
          "query":{}
        }).then(res => {
          loading.close()
          this.organizationList = res.data.data
        })
      },
      locationList() {
        this.$http.post(this.GLOBAL.host, {
          "method":"addressTree",
          "query":{}
        }).then(res => {
          this.locationList = res.data.data
        })
      },
      getOrganizationInfo() {
        this.$http.post(this.GLOBAL.host, {
          "method":"Emp_InitalData",
          "query":{}
        }).then(res => {
          this.positionList = res.data.data.positionBase
          this.postList = res.data.data.postBase
        })
      },
      handleNodeClick(a,b,c) {
      },
      selectOrganization(a,b,c) {
      },
      add() {
        this.form = {
          orgArrId: [],
        }
        this.orgTreeVisible = true
      },
      modify(data, node) {
        this.$http.post(this.GLOBAL.host, {
          "method":"Org_findById",
          "query":{ id: data.id }
        }).then(res => {
          this.form = res.data.data
          this.form.type = node.level
          this.orgTreeVisible = true
        })
      },
      remove(data, node) {
        this.$http.post(this.GLOBAL.host, {
          method:"Org_Delete",
          data:{ id: data.id }
        }).then(res => {
          if (res.data.code === 200) {
            const parent = node.parent;
            const children = parent.data.children || parent.data;
            const index = children.findIndex(d => d.id === data.id);
            children.splice(index, 1);
          } else {
            this.$message({
              message: res.data.data,
              type: 'error'
            });
          }
        })
      },
      renderContent(h, { node, data, store }) {
        if (node.level !== 1) {
        return (
          <span class="custom-tree-node">
            <span>{node.label}</span>
            <span class="custom-tree-node-option">
              <el-button size="mini" type="text" on-click={ () => this.modify(data, node) }>修改</el-button>
              <el-button size="mini" type="text" on-click={ () => this.remove(data, node) }>删除</el-button>
            </span>
          </span>
        )
      }
      node.expanded = true
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
        </span>
      )},
      onSubmit() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.form.id) {
              this.$http.post(this.GLOBAL.host, {
                method:"Org_Update",
                data: ({
                  ...this.form,
                  parentId: _.last(this.form.orgArrId) || 0,
                  region: this.form.addressArr[0],
                  province: this.form.addressArr[1],
                  city: this.form.addressArr[2],
                  level: this.form.orgArrId.length + 1,
                }),
              }).then(res => {
                if (res.data.code == 200) {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  });
                  this.orgTreeVisible = false
                  this.getData()
                } else {
                  this.$message({
                    message: res.data.data,
                    type: 'error'
                  });
                }
              })
            } else {
              this.$http.post(this.GLOBAL.host, {
                method:"Org_Add",
                data: ({
                  ...this.form,
                  parentId: _.last(this.form.orgArrId) || 0,
                  region: this.form.addressArr[0],
                  province: this.form.addressArr[1],
                  city: this.form.addressArr[2],
                  creator: this.$store.state.user.id,
                  level: this.form.orgArrId.length + 1,
                }),
              }).then(res => {
                if (res.data.code == 200) {
                  this.$message({
                    message: '创建成功',
                    type: 'success'
                  });
                  this.getData()
                  this.orgTreeVisible = false
                } else {
                  this.$message({
                    message: res.data.data,
                    type: 'error'
                  });
                }
              })
            }
          } else {
            return false;
          }
        });
      },
      onCancel() {
        this.$refs.form.resetFields()
        this.orgTreeVisible = false
      },
      onCancelAddPerson() {
        this.$refs.addPersonForm.resetFields()
        this.addPersonPanelVisible = false
      },
      addPerson() {
        this.addPersonForm = {
          addPersonOrg: [],
        },
        this.addPersonOrg = []
        this.addPersonPanelVisible = true
      },
      showPerson(rowData) {
        this.addPersonForm = _.clone(rowData)
        this.$set(this.addPersonForm, 'addPersonOrg', rowData.organizationId ?
          this.getPathByKey(rowData.organizationId, 'id', this.organizationList)
            .map(item => item.id) : [])
        this.addPersonPanelVisible = true
      },
      deletePerson(id) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$http.post(this.GLOBAL.host, {
          "method":"Emp_Delete",
          "data":{ id }
        }).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          loading.close()
          this.onSearch(undefined, this.lastQuery)
        })
      },
      submitPerson() {
        this.$refs['addPersonForm'].validate((valid) => {
          if (valid) {
            if (this.addPersonForm.id) {
              this.$http.post(this.GLOBAL.host, {
                method: "Emp_Update",
                data: {
                  ...this.addPersonForm,
                  organizationId: _.last(this.addPersonForm.addPersonOrg)
                }
              }).then(res => {
                if (res.data.code == 200) {
                  this.addPersonPanelVisible = false
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  });
                  this.onSearch(undefined, this.lastQuery)
                } else {
                  this.$message({
                    message: res.data.data,
                    type: 'error'
                  });
                }
              })
            } else {
              this.$http.post(this.GLOBAL.host, {
                method: "Emp_Add",
                data: {
                  ...this.addPersonForm,
                  organizationId: _.last(this.addPersonForm.addPersonOrg)
                }
              }).then(res => {
                if (res.data.code == 200) {
                  this.addPersonPanelVisible = false
                  this.$message({
                    message: '创建成功',
                    type: 'success'
                  });
                  this.onSearch(undefined, this.lastQuery)
                } else {
                  this.$message({
                    message: res.data.data,
                    type: 'error'
                  });
                }
              })
            }
          }
        })
      },
      onSearch(pageNum, lastQuery) {
        this.lastQuery = lastQuery || {
          pageNo: pageNum || 1,
          pageSize: 10,
          organizationId: _.last(this.selectedOrgForDetail),
          postId: this.postId,
          keyword: this.filterStr,
        }
        this.$http.post(this.GLOBAL.host, {
          method:"getEmployeeList",
          query: this.lastQuery,
          }
        ).then(res => {
          this.tableData = res.data.data.list
          this.total = res.data.data.total
        })
      },
      importData() {
        this.$http.post(this.GLOBAL.host, {
            method:"Org_Download",
          }
        )
      },
      onUpload(res) {
        if (res.code == 200) {
          this.$message({
            message: res.data,
            type: 'success',
            showClose: true,
            duration: 0,
          });
          this.onSearch(undefined, this.lastQuery)
        } else {
          this.$message({
            message: res.data || '上传失败',
            type: 'error',
            showClose: true,
            duration: 0,
          });
        }
      },
      getPathByKey(value, key, arr) {
        let temppath = [];
        try {
          function getNodePath(node){
            temppath.push(node);
            //找到符合条件的节点，通过throw终止掉递归
            if (node[key] === value) {
              throw ("GOT IT!");
            }
            if (node.children && node.children.length > 0) {
              for (var i = 0; i < node.children.length; i++) {
                getNodePath(node.children[i]);
              }

              //当前节点的子节点遍历完依旧没找到，则删除路径中的该节点
              temppath.pop();
            }
            else {

              //找到叶子节点时，删除路径当中的该叶子节点
              temppath.pop();
            }
          }
          for (let i = 0; i < arr.length; i++) {
            getNodePath(arr[i]);
          }
        } catch (e) {
          return temppath;
        }
      }
    }
  }
</script>

<style lang="less">
  .org-breadcrumb {
    padding: 15px;
  }
  .org-container {
    background-color: #e0e8ef;
    padding: 10px;
    font-size: 16px;
  }
  .org-content {
    padding: 10px;
    background-color: white;
    overflow: hidden;
  }
  .org-header {
    line-height: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
  .org-body {
    display: flex;
  }
  .org-tree {
    flex-basis: 240px;
    min-height: 600px;
    flex-grow: 0;
    flex-shrink: 0;
    border: 1px solid #e0e8ef;
    border-radius: 5px;

    .tree-header {
      display: flex;
      justify-content: space-between;
      padding: 0 15px;
      line-height: 40px;
      background-color: #e0e8ef;
    }
  }
  .custom-tree-node-option {
    padding-left: 20px;
  }
  .org-operation {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    margin-bottom: 10px;
  }
  .org-position {
    display: flex;
    flex-basis: 170px;
    flex-grow: 0;
    flex-shrink: 0;
    align-items: center;
    > span {
      flex: 60px 1 0;
    }
  }
  .org-filter {
    flex: 150px 0 0;
  }
  .org-list {
    padding: 10px 20px;
    flex: 1;
    overflow: hidden;
    /*width: calc(100% - 260px);*/
    .el-upload__input {
      display: none;
    }
  }
  .dialog-footer {
    text-align: center;
  }
  .upload-demo {
    display: inline-block;
  }
  .org-list-cascader {
    width: 140px;
  }
  .org-label {
    font-size: 14px;
    display: inline-block;
  }
  .org-link {
    color: #66b1ff;
    font-size: 12px;
    &:hover {
      color: #66b1ff;
      text-decoration: none;
    }
  }
</style>
